package com.zkyc.framework.website.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.api.R;
import com.google.gson.JsonObject;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.zkyc.framework.common.constant.NumberConstant;
import com.zkyc.framework.common.exception.ResultCode;
import com.zkyc.framework.common.mapper.ApproveMapper;
import com.zkyc.framework.common.mapper.PiMapper;
import com.zkyc.framework.common.mapper.UserMapper;
import com.zkyc.framework.common.pojo.*;
import com.zkyc.framework.common.utils.PageUtil;
import com.zkyc.framework.common.vo.ResultVO;
import com.zkyc.framework.common.vo.website.ApprovePageVO;
import com.zkyc.framework.common.vo.website.ApproveProcessContentVO;
import com.zkyc.framework.common.vo.website.QuoteVO;
import com.zkyc.framework.website.mapper.ContentMapper;
import com.zkyc.framework.website.mapper.QuoteMapper;
import com.zkyc.framework.website.service.ApproveProcessService;
import com.zkyc.framework.website.service.ApproveService;
import com.zkyc.framework.website.service.ColumnService;
import com.zkyc.framework.website.util.TokenUserUtil;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * (Approve)表服务实现类
 *
 * @author libingchuan
 * @since 2023-02-15 16:01:31
 */
@Service("approveService")
public class ApproveServiceImpl implements ApproveService {
    @Resource
    private ApproveProcessService approveProcessService;

    @Resource
    private ApproveMapper approveMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ContentMapper contentMapper;

    @Autowired
    private QuoteMapper quoteMapper;

    @Autowired
    private PiMapper piMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Approve queryById(Integer id) {
        return this.approveMapper.selectById(id);
    }

    /**
     * 分页查询
     *
     * @return 查询结果
     */
    @Override
    public ResultVO queryByPage(ApprovePageVO approvePageVo) {
        if (approvePageVo == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        approvePageVo.checkParam();
        String status = approvePageVo.getStatus();
        if (StringUtils.isEmpty(status)) {
            approvePageVo.setStatus(StringPool.ZERO);
        }
        if (StringUtils.isEmpty(approvePageVo.getType())) {
            approvePageVo.setType(StringPool.ONE);
        }
        String level = null;
        String centerId = null;
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(approveProcessService.judgeIdentity().getData());
        switch (approvePageVo.getType()) {
            case "1":
                String permission = jsonObject.getString("1");
                if (StringUtils.isEmpty(permission)) return ResultVO.data(PageUtil.getPages(approvePageVo.getPage(), approvePageVo.getSize(), new ArrayList()));
                if (!approvePageVo.getType().equals("3") && permission.equals("0")) {
                    return ResultVO.data(PageUtil.getPages(approvePageVo.getPage(), approvePageVo.getSize(), new ArrayList()));
                }
                HashMap<String, String> map = setCenterAndLevel(permission);
                if (status.equals("3")) {
                    map.put("level", "2");
                    status = null;
                }
                String showStatus = approvePageVo.getShowStatus();
                List<ApproveProcessContentVO> approveProcessContentVOS = approveMapper.contentList(map.get("level"),
                        map.get("centerId"), status, approvePageVo.getId(), approvePageVo.getCreatedBy(),
                        approvePageVo.getContentTitle(), approvePageVo.getColumnName(), showStatus);
                for (ApproveProcessContentVO approveProcessContentVO : approveProcessContentVOS) {
                    List<WebQuoteContent> webQuoteContents = quoteMapper.selectList(new LambdaQueryWrapper<WebQuoteContent>()
                            .eq(WebQuoteContent::getContentId, approveProcessContentVO.getId()));
                    if (webQuoteContents.size() > 0) {
                        Approve approve = approveMapper.selectOne(new LambdaQueryWrapper<Approve>().eq(Approve::getPid, webQuoteContents.get(0).getContentId())
                                .eq(Approve::getType, 3));
                        if (approve != null) {
                            approveProcessContentVO.setStatus(approve.getStatus());
                        }
                    } else {
                        WebContent webContent = contentMapper.selectById(approveProcessContentVO.getId());
                        if (webContent != null) {
                            if (webContent.getStatus() == 0) {
                                //3 未发布
                                approveProcessContentVO.setStatus(3);
                            } else if (webContent.getStatus() == 1) {
                                //4 已发布
                                approveProcessContentVO.setStatus(4);
                            } else if (webContent.getStatus() == 2) {
                                //2 驳回
                                approveProcessContentVO.setStatus(2);
                            } else if (webContent.getStatus() == 4) {
                                //4 待处理
                                approveProcessContentVO.setStatus(5);
                            }
                        }
                    }
                }
                if (StringUtils.isNotBlank(showStatus)) {
                    approveProcessContentVOS.removeIf(x -> Integer.parseInt(showStatus) == 4 ? (x.getStatus() != 2 && x.getStatus() != 4) :
                            x.getStatus() != Integer.parseInt(showStatus));
                }
                return ResultVO.data(PageUtil.getPages(approvePageVo.getPage(), approvePageVo.getSize(), approveProcessContentVOS));
            case "2":
                permission = jsonObject.getString("2");
                if (StringUtils.isEmpty(permission)) return ResultVO.data(PageUtil.getPages(approvePageVo.getPage(), approvePageVo.getSize(), new ArrayList()));
                if (!approvePageVo.getType().equals("3") && permission.equals("0")) {
                    return ResultVO.data(PageUtil.getPages(approvePageVo.getPage(), approvePageVo.getSize(), new ArrayList()));
                }
                HashMap<String, String> map1 = setCenterAndLevel(permission);
                if (status.equals("3")) {
                    map1.put("level", "2");
                    status = null;
                }
                return ResultVO.data(PageUtil.getPages(approvePageVo.getPage(), approvePageVo.getSize(),
                        JSONArray.parseArray(JSON.toJSONString(approveMapper.piList(map1.get("level"), map1.get("centerId")
                                , approvePageVo.getCenterName(), approvePageVo.getOrganizationName(), status), SerializerFeature.WriteDateUseDateFormat))));
            case "3":
                JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(approveMapper.quoteList(approvePageVo.getCenterId(), status
                        , approvePageVo.getId(), approvePageVo.getCreatedBy(), approvePageVo.getContentTitle()
                        , approvePageVo.getColumnName()), SerializerFeature.WriteDateUseDateFormat));
                for (int i = 1; i < jsonArray.size(); i++) {
                    JSONObject result = jsonArray.getJSONObject(i);
                    JSONObject resuleOld = jsonArray.getJSONObject(i - 1);
                    if (result.get("id").equals(resuleOld.get("id"))) {
                        String qutoeTo = resuleOld.get("quoteTo") + "," + result.get("quoteTo");
                        resuleOld.put("quoteTo", qutoeTo);
                        jsonArray.remove(i);
                        --i;
                    }
                }
                return ResultVO.data(PageUtil.getPages(approvePageVo.getPage(), approvePageVo.getSize(), jsonArray));
        }
        return ResultVO.fail(ResultCode.PARAM_INVALID);
    }

    public HashMap setCenterAndLevel(String permission) {
        HashMap<String, String> map = new HashMap<String, String>();
        String level = null;
        String centerId = null;
        switch (permission) {
            case "1":
                level = "1";
                centerId = userMapper.selectById(TokenUserUtil.getCurrentUserId()).getCenterId().toString();
                break;
            case "2":
                level = "2";
                centerId = userMapper.selectById(TokenUserUtil.getCurrentUserId()).getCenterId().toString();
                break;
        }
        map.put("level", level);
        map.put("centerId", centerId);
        return map;
    }

    /**
     * 查询
     *
     * @return 查询结果
     */
    @Override
    public ResultVO queryList() {
        return ResultVO.data(approveMapper.selectList(null));
    }


    /**
     * 新增数据
     *
     * @param approve 实例对象
     * @return 实例对象
     */
    @Override
    public ResultVO insert(Approve approve) {
        if (approve == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        approveMapper.insert(approve);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    /**
     * 修改数据
     *
     * @param approve 实例对象
     * @return 实例对象
     */
    @Override
    public ResultVO update(Approve approve) {
        if (approve == null && approve.getId() == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        if (queryById(approve.getId()) == null) {
            return ResultVO.fail(ResultCode.SERVE_ERROR);
        }
        approveMapper.updateById(approve);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public ResultVO deleteById(Integer id) {
        if (id == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        if (queryById(id) == null) {
            return ResultVO.fail(ResultCode.SERVE_ERROR);
        }
        approveMapper.deleteById(id);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO approve(Integer id, Integer status, String remark, Integer type) {
        Approve approve = approveMapper.selectOne(new LambdaQueryWrapper<Approve>().eq(Approve::getPid, id).eq(Approve::getType, type));
        if (approve == null) {
            return ResultVO.fail(ResultCode.NO_APPROVE_INFORMATION);
        }
        if (StringUtils.isNotBlank(remark)) {
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(approveProcessService.judgeIdentity().getData());
            String permission = jsonObject.getString(type.toString());
            if (StringUtils.isNotBlank(permission)) {
                switch (permission) {
                    case "1":
                        approve.setRemark1(remark);
                        break;
                    case "2":
                        approve.setRemark2(remark);
                        break;
                }
            }
        }
        switch (type) {
            case 1:
                WebContent webContent = contentMapper.selectById(id);
                switch (status) {
                    case 1:
                        webContent.setStatus(0);
                        approve.setApproveDate(new Date());
                        approve.setStatus(status);
                        break;
                    case 2:
                        approve.setApproveDate(new Date());
                        webContent.setStatus(2);
                        approve.setStatus(status);
                        break;
                    case 3:
                        approve.setTransmitDate(new Date());
                        approve.setLevel(2);
                        break;
                }
                contentMapper.updateById(webContent);
                approveMapper.updateById(approve);
                break;
            case 2:
                Pi pi = piMapper.selectById(id);
                switch (status) {
                    case 1:
                        pi.setIsVerified(1);
                        approve.setApproveDate(new Date());
                        break;
                    case 2:
                        approve.setApproveDate(new Date());
                        pi.setIsVerified(2);
                        break;
                    case 3:
                        approve.setTransmitDate(new Date());
                        approve.setLevel(2);
                        status = 0;
                        break;
                }
                piMapper.updateById(pi);
                approve.setStatus(status);
                approveMapper.updateById(approve);
                break;
            case 3:
                List<WebQuoteContent> webQuoteContents = quoteMapper.selectList(new LambdaQueryWrapper<WebQuoteContent>().eq(WebQuoteContent::getContentId, id));
                for (WebQuoteContent webQuoteContent : webQuoteContents) {
                    webQuoteContent.setStatus(status);
                    quoteMapper.updateById(webQuoteContent);
                }
                approve.setStatus(status);
                approve.setRemark1(remark);
                approve.setApproveDate(new Date());
                approveMapper.updateById(approve);
                break;
        }
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO detail(Integer id, Integer type) {
        switch (type) {
            case 1:
                return ResultVO.data(approveMapper.contentDetail(id.toString()));
            case 2:
                return ResultVO.data(JSONObject.parseObject(JSON.toJSONString(approveMapper.piDetail(id.toString()), SerializerFeature.WriteDateUseDateFormat)));
            case 3:
                return ResultVO.data(approveMapper.quoteDetail(id.toString()));
        }
        return ResultVO.fail(ResultCode.FAILURE);
    }

    @Override
    public ResultVO recommend(QuoteVO quoteVO) {
        List<Integer> columnIds = quoteVO.getColumnIds();
        Integer id = null;
        Integer centerId = null;
        String createdBy = null;
        for (Integer columnId : columnIds) {
            QueryWrapper<WebQuoteContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("column_id", columnId);
            queryWrapper.eq("content_id", quoteVO.getContentId());
            WebQuoteContent sqlQuote = quoteMapper.selectOne(queryWrapper);
            if (sqlQuote != null) {
                if (sqlQuote.getStatus() != 2) {
                    return ResultVO.fail("已引用该文章");
                } else {
                    //否则重启流程
                    quoteMapper.deleteById(sqlQuote.getId());
                    approveMapper.delete(new LambdaQueryWrapper<Approve>().eq(Approve::getPid, sqlQuote.getContentId())
                            .eq(Approve::getType, 3));
                }
            }
            WebQuoteContent webQuoteContent = new WebQuoteContent();
            webQuoteContent.setContentId(quoteVO.getContentId());
            webQuoteContent.setColumnId(columnId);
            Date date = new Date();
            webQuoteContent.setGmtUpdated(date);
            webQuoteContent.setGmtCreated(date);
            webQuoteContent.setStatus(0);
            quoteMapper.insert(webQuoteContent);
            WebContent webContent = contentMapper.selectById(quoteVO.getContentId());
            id = webContent.getId();
            centerId = webContent.getCenterId();
            createdBy = webContent.getCreatedBy();

        }
        Approve approve = new Approve();
        approve.setCenterId(centerId);
        approve.setLevel(3);
        approve.setType(3);
        approve.setCreatedBy(createdBy);
        approve.setStatus(0);
        approve.setPid(id);
        approveMapper.insert(approve);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    public String setRejectReason(Integer id, Integer type) {
        Approve approve = approveMapper.selectOne(new LambdaQueryWrapper<Approve>().eq(Approve::getPid, id).eq(Approve::getType, type));
        if (approve != null) {
            Integer status = approve.getStatus();
            Integer level = approve.getLevel();
            if (status == 2) {
                if (level == 1 && approve.getRemark1() != null) {
                    return approve.getRemark1();
                } else if (level == 2 && approve.getRemark2() != null) {
                    return approve.getRemark2();
                }
            }
        }
        return null;
    }


}
